package com.zmn.oms.zmn.business.impl.open;


import com.zmn.base.common.data.common.dro.area.AreaDRO;
import com.zmn.base.common.data.dubbo.interfaces.area.AreaListRemoteService;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.manager.redis.RedisManager;
import com.zmn.oms.business.interfaces.baidumap.BaiduMapBService;
import com.zmn.oms.business.interfaces.log.OrderLogBService;
import com.zmn.oms.business.interfaces.remark.OrderRemarkBService;
import com.zmn.oms.business.interfaces.work.OrderWorkListBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.dto.baidumap.LngLatLocation;
import com.zmn.oms.model.dto.order.open.CreateOrderDTO;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.vo.work.ZsOrderWorkVO;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.order.OrderExtendService;
import com.zmn.oms.services.interfaces.order.OrderService;
import com.zmn.oms.services.interfaces.product.OrderProductService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.business.interfaces.proxy.ProxyOrderBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkOperatePermissionBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkQueryBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkScheduleBService;
import com.zmn.oms.zmn.normal.business.interfaces.order.ZsNormalOrderBService;
import com.zmn.oms.zmn.normal.business.interfaces.serviceitem.ZsNormalOrderServiceItemBService;
import com.zmn.oms.zmn.normal.business.interfaces.work.ZsNormalOrderWorkAmountBService;
import com.zmn.oms.zmn.normal.business.interfaces.work.ZsNormalWorkBService;
import com.zmn.oms.zmn.normal.business.interfaces.work.masterwork.ZsNormalMasterWorkBService;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;
import java.util.Optional;

/**
 * 类描述：订单接口
 *
 * @author liuying
 * @date 2019/03/19 15:53
 */
public abstract class OpenOrderBaseBServiceImpl {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    private AreaListRemoteService areaListRemoteService;

    @Autowired
    ZsNormalOrderBService zsNormalOrderBService;
    @Autowired
    ZsNormalOrderWorkAmountBService zsNormalOrderWorkAmountBService;
    @Autowired
    ZsNormalMasterWorkBService zsNormalMasterWorkBService;
    @Autowired
    OrderWorkService orderWorkService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    OrderService orderService;
    @Autowired
    OrderProductService orderProductService;
    @Autowired
    ZsNormalWorkBService zsNormalWorkBService;
    @Autowired
    OrderWorkListBService orderWorkListBService;
    @Autowired
    ZsOrderWorkOperatePermissionBService zsOrderWorkOperatePermissionBService;
    @Autowired
    OrderExtendService orderExtendService;
    @Autowired
    OrderRemarkBService orderRemarkBService;
    @Autowired
    ZsOrderWorkScheduleBService zsOrderWorkScheduleBService;
    @Autowired
    OrderLogBService orderLogBService;
    @Autowired
    RedisManager redisManager;
    @Autowired
    ZsOrderWorkQueryBService zsOrderWorkQueryBService;
    @Autowired
    ProxyOrderBService proxyOrderBService;
    @Autowired
    private BaiduMapBService baiduMapBService;
    @Autowired
    ZsNormalOrderServiceItemBService zsNormalOrderServiceItemBService;

    /**
     * 获取订单
     *
     * @param channelId
     * @param oderId
     * @return
     */
    OrderWork requireChannelOrder(Integer channelId, Long oderId) throws OmsBaseException {

        if (oderId == null) {
            throw new OmsBaseException("订单ID不能为空");
        }

        // 查询历史订单
        OrderWork dbOrderWork = orderWorkService.findOrderWorkByKey(oderId, oderId);

        if (dbOrderWork == null) {
            throw new OmsBaseException("订单不存在");
        }

        if (!Objects.equals(channelId, dbOrderWork.getChannelId())) {
            throw new OmsBaseException("订单渠道不匹配");
        }

        return dbOrderWork;
    }

    ZsOrderWorkVO getChannelOrderByOuterId(Integer channelId, String outerId) throws OmsBaseException {
        if (channelId == null) {
            throw new OmsBaseException("非法渠道");
        }

        if (StringUtils.isBlank(outerId)) {
            return null;
        }

        return zsOrderWorkQueryBService.findOrderWorkByOuterId(outerId,channelId);

        /*
        OrderWorkQuery query = new OrderWorkQuery();
        query.setOuterId(outerId);
        query.setChannelIdList(Lists.newArrayList(channelId));
        query.setPageSize(1);
        query.setPageIndex(1);
        List<EsOrderWork> esOrderWorkList = orderWorkListBService.listPageOrderWorkByQuery(query);
        if (CollectionUtils.isEmpty(esOrderWorkList)) {
            return null;
        }
        return esOrderWorkList.get(0);
        */
    }

    /**
     * 准备标准的接口录单数据：将接口传过来的数据进行处理，补全缺失的，修正冲突的，使其成为符合要求的录单数据
     * @param createOrderDTO
     * @return
     */
    CreateOrderDTO preparedForCreateOrderData(CreateOrderDTO createOrderDTO) {
        // 当渠道没传经纬度时，通过地址反解析一次经纬度
        if (createOrderDTO.getLatitude() == null || createOrderDTO.getLongitude() == null) {
            try {
                ResponseDTO<AreaDRO> areaResponse = areaListRemoteService.getById(createOrderDTO.getCityId());
                AreaDRO areaDRO = areaResponse.getData();
                if ( areaDRO != null && (StringUtils.isNotBlank(areaDRO.getName())) ) {

                    String addressStr = Optional.ofNullable(createOrderDTO.getStreet()).orElse("")
                            + Optional.ofNullable(createOrderDTO.getAddress()).orElse("");

                    // 修正地址文本
                    String address = addressStr.replaceAll(" ", "");
                    if (!address.contains(areaDRO.getName())) {
                        address = areaDRO.getName() + address;
                    }

                    LngLatLocation location = baiduMapBService.location(address);
                    if (location != null) {
                        createOrderDTO.setLatitude(Double.valueOf(location.getLat()));
                        createOrderDTO.setLongitude(Double.valueOf(location.getLng()));
                    }
                }
            } catch (Exception e) {
                // 反解析经纬度失败，不做处理
            }
        }

        // 存在预付款的订单，忽略返修单标志，保存为新单（返修单价格永远为0）
        if (Objects.equals(OrderConsts.ORDER_TYPE_REWORK, createOrderDTO.getType())
                && !NumberUtil.isNullOrZero(createOrderDTO.getChannelPrepayAmount())) {
            createOrderDTO.setType(OrderConsts.ORDER_TYPE_NEW);
        }

        // 姓名为空默认塞“未知”（背景：修改工单时姓名是必填，若为空则需要派单员手动填写姓名，增加时间成本） 2020-05-18 by lhl
        if (StringUtil.isBlank(createOrderDTO.getContactName())) {
            createOrderDTO.setContactName("未知");
        }

        return createOrderDTO;
    }
}
